from django.shortcuts import render
from django.views import View
import json,base64,pickle
from django import http
from django_redis import get_redis_connection
from goods.models import SKU
# Create your views here.

def get_carts_from_cookies(request):
    # 获取cookie中的数据
    # 可以设置一个cookie 存储数据
    carts_from_cookie = request.COOKIES.get('carts')

    if carts_from_cookie:
        cart_dict = base64.b64decode(carts_from_cookie.encode())
        cart_dict = pickle.loads(cart_dict)
        return cart_dict
    else:
        return {}


def get_cookie_cart_data(cookie_cart):
    # 编码
    return  base64.b64encode(pickle.dumps(cookie_cart)).decode()

def get_redis_carts(request):
    user_id = request.user.id
    redis_cart = None
    redis_selected = None
    conn = get_redis_connection('carts')

    redis_cart = conn.hgetall('carts_%s' % user_id)
    redis_selected = conn.smembers('selected_%s' % user_id)

    if not redis_cart:
        redis_cart = {}
    if not redis_selected:
        redis_selected = set()
    return  redis_cart,redis_selected



class CartSelectAllView(View):
    def put(self,request):
        data = json.loads(request.body.decode())
        selected = data.get('selected')
        if not isinstance(selected,bool):
            return http.JsonResponse({
                'code': 400,
                'errmsg': '数据错误'
            })
        if request.user.is_authenticated:
            conn = get_redis_connection('carts')

            redis_cart,redis_seleted = get_redis_carts(request)

            sku_id = redis_cart.keys()
            if selected:
                conn.sadd('selected_%s' % request.user.id,*sku_id)
            else:
                conn.srem('selected_%s' % request.user.id,*sku_id)
            return http.JsonResponse({'code': 0, 'errmsg': 'ok'})


        else:
            cookie_cart = get_carts_from_cookies(request)

            sku_ids = cookie_cart.keys()

            for sku_id in sku_ids:
                cookie_cart[sku_id]['selected'] = selected
            data = get_cookie_cart_data(cookie_cart)
            response = http.JsonResponse({'code': 0, 'errmsg': 'ok'})
            response.set_cookie(
                'carts',
                data
            )
            return response


class CartsView(View):

    def delete(self,request):
        data = json.loads(request.body.decode())
        sku_id = data.get('sku_id')

        if request.user.is_authenticated:
            conn = get_redis_connection('carts')
            conn.hdel('carts_%s' % request.user.id,sku_id)
            conn.srem('selected_%s' % request.user.id,sku_id)
            return http.JsonResponse({
                'code': 0,
                'errmsg': 'ok'
            })
        else:
            cookie_cart = get_carts_from_cookies(request)
            del cookie_cart[sku_id]
            data = get_cookie_cart_data(cookie_cart)
            response = http.JsonResponse({
                'code': 0,
                'errmsg': 'ok'
            })
            response.set_cookie(
                'carts',
                data
            )
            return response


    def put(self,request):
        data = json.loads(request.body.decode())
        sku_id = data.get('sku_id')
        count = data.get('count')
        selected = data.get('selected', True)

        # 2、校验参数
        if not all([sku_id, count]):
            return http.JsonResponse({'code': 400, 'errmsg': '缺少参数！'})

        if isinstance(sku_id, str) and not sku_id.isdigit():
            return http.JsonResponse({'code': 400, 'errmsg': '参数错误！'})

        if isinstance(count, str) and not count.isdigit():
            return http.JsonResponse({'code': 400, 'errmsg': '参数错误！'})

        if not isinstance(selected, bool):
            return http.JsonResponse({'code': 400, 'errmsg': '参数错误！'})

        if request.user.is_authenticated:
            conn =get_redis_connection('carts')

            conn.hset('carts_%s' % request.user.id,sku_id,count)
            if selected:
                conn.sadd('selected_%s' % request.user.id,sku_id)
            else:
                conn.srem('selected_%s' % request.user.id,sku_id)
            return http.JsonResponse({
                'code':0,
                'errmsg': 'ok',
                'cart_sku':{
                    'id': sku_id,
                    'count':count,
                    'selected': selected
                }
            })

        else:
            cookie_cart = get_carts_from_cookies(request)

            cookie_cart[sku_id]['count'] = count
            cookie_cart[sku_id]['selected'] = selected

            data = get_cookie_cart_data(cookie_cart)
            response = http.JsonResponse({
                'code': 0,
                'errmsg': 'ok',
                'cart_sku': {
                    'id': sku_id,
                    'count': count,
                    'selected': selected
                }
            })

            response.set_cookie('carts',data)
            return response






    def get(self,request):

        cart_dict= {}
        if request.user.is_authenticated:
            redis_cart,redis_selected = get_redis_carts(request)
            for sku_id,count in redis_cart.items():

                cart_dict[int(sku_id)] = {
                    'count': int(count),
                    'selected': sku_id in redis_selected
                }
        else:
            cart_dict = get_carts_from_cookies(request)

        sku_ids = cart_dict.keys()

        carts_skus = []
        for sku_id in sku_ids:
            sku = SKU.objects.get(pk=sku_id)
            carts_skus.append({
                'id':sku.id,
                'name':sku.name,
                'selected': cart_dict[sku_id]['selected'],
                'default_image_url': sku.default_image_url,
                'price': sku.price,
                'count': cart_dict[sku_id]['count'],
                # 'amount': sku.price * cart_dict[sku_id]['count']

            })
        return http.JsonResponse({
            'code': 0,
            'errmsg': 'ok',
            'cart_skus': carts_skus

        })


    def post(self,request):
        data_dict = json.loads(request.body.decode())

        sku_id = data_dict.get('sku_id')
        count = data_dict.get('count')
        selected = data_dict.get('selected',True)

        if not all([sku_id,count]):
            return http.JsonResponse({'code': 400, 'errmsg': '缺少参数！'})

        if isinstance(sku_id,str) and not sku_id.isdigit():
            return http.JsonResponse({'code': 400, 'errmsg': '缺少参数！'})
        if not isinstance(selected,bool):
            return http.JsonResponse({'code': 400, 'errmsg': '缺少参数！'})

        # 如果已登录
        if request.user.is_authenticated:
            conn = get_redis_connection('carts')
            conn.hincrby('carts_%s' % request.user.id,sku_id,count)
            if selected:
                conn.sadd('selected_%s'%request.user.id,sku_id)
            else:
                conn.srem('selected_%s'%request.user.id,sku_id)
            return http.JsonResponse({'code': 0, 'errmsg': 'ok'})


        # 未登录 获取cookie中的数据

        cookie_cart = get_carts_from_cookies(request)
        if sku_id in cookie_cart:
            cookie_cart[sku_id]['count'] = count
            cookie_cart[sku_id]['selected'] = selected

        else:
            cookie_cart[sku_id]={
                'count':count,
                'selected': selected
            }

        # 将新增购物车数据存到cookie
        data = get_cookie_cart_data(cookie_cart)

        response = http.JsonResponse({'code': 0, 'errmsg': 'ok'})
        response.set_cookie('carts',data)
        return response
